package com.streaminggbs.common.base;


import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import cn.hutool.core.bean.BeanUtil;
import com.streaminggbs.entity.LoginUser;
import com.streaminggbs.entity.SysAuthUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;

/**
 * @author lilin
 */
@ControllerAdvice
@Slf4j
public class TokenHandler {
	
	@ModelAttribute
	public LoginUser getLoginUser(HttpServletRequest request
                               ) throws UnsupportedEncodingException {
		String path = request.getRequestURL().toString();
//		log.info("TokenHandler getUser -----------------------path: " + path);

        boolean login = path.contains("/login");
        boolean logout = path.contains("/logout");
        boolean error = path.contains("/error");
        boolean swagger = path.contains("/swagger");
        boolean v2 = path.contains("/v2/");
        boolean check = path.contains("/check");
//        boolean getUserInfo = path.contains("/user/getUserInfo");
        if (login || logout || error || swagger || v2 || check/*|| getUserInfo*/) {
            return null;
        }

        HttpSession session = request.getSession();
        if(session == null){
            log.info("当前用户未登录");
            throw new ErrorCodeException(2000,"用户未登陆!");
        }
        SysAuthUser user = (SysAuthUser) session.getAttribute("user");
        if(user == null){
            log.info("当前用户未登录");
            throw new ErrorCodeException(2000,"用户未登陆!");
        }

        LoginUser loginUser = new LoginUser();
        if(loginUser.getSysUser() == null){
            loginUser.setSysUser(new SysAuthUser());
        }
        BeanUtil.copyProperties(user, loginUser.getSysUser());

		return loginUser;
	}
}
